import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '@/store'
// 导入组件
// import upReg from '../views/Reg/Reg.vue'
// import upMain from '@/views/Main/Main.vue'
// import upHome from '@/views/Menus/Home/Home.vue'
// import UserInfo from '@/views/Menus/User/UserInfo.vue'
// import UserAvatar from '@/views/Menus/User/UserAvatar.vue'
// import UserPwd from '@/views/Menus/User/UserPwd.vue'
// import ArtCate from '@/views/Menus/Artcle/ArtCate.vue'
// import ArtList from '@/views/Menus/Artcle/ArtList.vue'
// import upLogin from '../views/Login/Login.vue'
// // 移除静态导入，改用动态导入
const upReg = () => import('../views/Reg/Reg.vue')
const upLogin = () => import('../views/Login/Login.vue')
const upMain = () => import('@/views/Main/Main.vue')
const upHome = () => import('@/views/Menus/Home/Home.vue')
const UserInfo = () => import('@/views/Menus/User/UserInfo.vue')
const UserAvatar = () => import('@/views/Menus/User/UserAvatar.vue')
const UserPwd = () => import('@/views/Menus/User/UserPwd.vue')
const ArtCate = () => import('@/views/Menus/Artcle/ArtCate.vue')
const ArtList = () => import('@/views/Menus/Artcle/ArtList.vue')
Vue.use(VueRouter)
// 解决重复点击路由报错问题
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push (location) {
  return originalPush.call(this, location).catch(err => err)
}

const routes = [
  {
    path: '/reg',
    component: upReg
  },
  {
    path: '/login',
    component: upLogin
  },
  {
    path: '/',
    component: upMain,
    redirect: '/home',
    children: [
      {
        path: 'home',
        component: upHome
      }, {
        path: 'user-info',
        component: UserInfo
      },
      {
        path: 'user-avatar',
        component: UserAvatar
      },
      {
        path: 'user-pwd',
        component: UserPwd
      }, {
        path: 'art-cate',
        component: ArtCate
      },
      {
        path: 'art-list',
        component: ArtList
      }
    ]
  }
]

const router = new VueRouter({
  routes
})
// 导航守卫
// to: 要去的路由
// from: 从哪个路由来
// next: 是否放行
router.beforeEach((to, from, next) => {
  // 获取token
  const token = store.state.user.token
  // 判断是否登录，没登陆跳转登录页
  // 没登陆并且要去的页面不是登录页或者注册页
  // 可以把登录和注册页加入到白名单中
  const whiteList = ['/login', '/reg']
  if (!token && !whiteList.includes(to.path)) {
    Vue.prototype.$message.warning('请先登录')
    return next('/login')
  } else {
    next()
  }
})
export default router
